import { CommonModal } from '@/pages/OrderModule/common/components/CommonModal';
import CommonInput from '@/pages/OrderModule/common/components/CommonInput';
import { Button, Form, Modal, Row, Col } from 'antd';
import { find } from 'lodash';
import { useEffect, useRef, useState } from 'react';
import GoodsFilterForm from './GoodsFilterForm';
import GoodsShowTable from './GoodsShowTable';
import { TableType } from './helpers/constant';

/**
 *
 * type字段 选择商品组件组件分别是
    1. 新增商品（无数量）：即无数量的输入框
    2. 新增商品（有数量）：即有数量的输入框
    3. 新增款式商品：统一无数量，只是选择一整个款
 */
const GoodsSelectModal = (props) => {
    const { children, setSelectedRows = () => [], submitCallback, handleSubmitAllInfo, getInputNumberValues, title = '新增商品', type = TableType.NoNumberInput, handleCancel, isSingle, node } = props;
    if (typeof submitCallback !== 'function') {
        throw new Error('submitCallback is required');
    }
    if (type === TableType.HasNumberInput && typeof getInputNumberValues !== 'function') {
        console.error('getInputNumberValues is required when type is HasNumberInput');
    }
    const [filterParams, setFilterParams] = useState({});
    const [show, toggleShow] = useState(false);
    const [form] = Form.useForm();
    const btn = children || <Button>新增商品</Button>;
    const curRows = useRef([]);
    const curInputNumberValues = useRef({});
    const stageParams = useRef({
        dataSource: [],
        selectedRowKeys: []
    });
    //缓存
    const commonChange = (type, value) => {
        stageParams.current = {
            ...stageParams.current,
            [type]: value
        }
    }

    const getTableRows = (values) => {
        curRows.current = values;
    };
		useEffect(() => {
			handleCancel && toggleShow(true);
		}, [])
    const handleSubmit = () => {
        if (curRows.current.length === 0) {
          Modal.error({ content: "请选择商品" });
          return;
        }
  
        toggleShow(false);
        if(handleSubmitAllInfo){//勾选的和填充数量的
          const { dataSource, selectedRowKeys } = stageParams.current;
          const numObj = curInputNumberValues.current;
          const allGoodsIds = [...new Set([...selectedRowKeys, ...Object.keys(numObj)])], allGoodsInfo = [];
          allGoodsIds.map(item=>{
            const obj = find(dataSource, ['id', item]);
            if(obj){
                allGoodsInfo.push({...obj, goodsNum: numObj[item] || 1});
            }
          })
          handleSubmitAllInfo(allGoodsInfo);
        }
        submitCallback && submitCallback(curRows.current, curInputNumberValues.current);
        getInputNumberValues && getInputNumberValues(curInputNumberValues.current);
    };
    const openModal = () => {
        toggleShow(true);
        curRows.current = [];
    };
    const closeModal = () => {
        toggleShow(false);
				handleCancel && handleCancel();
    };
    // const modalFooter = (
    //   <Row>
    //     <Col span={21}>
    //       <CommonInput placeholder="请输入商品编码，多个商品编码以逗号隔开" showEditIcon></CommonInput>
    //     </Col>
    //     <Col span={3}>
    //       <Button onClick={closeModal}>取消</Button>
    //       <Button onClick={handleSubmit} type="primary">
    //         确定
    //       </Button>
    //     </Col>
    //   </Row>
    // );

    return (<>
      <span onClick={openModal}>{btn}</span>
      <CommonModal title={{ title }} open={show} onOk={handleSubmit} onCancel={closeModal} width={1600} destroyOnClose 
        style={{ position: 'absolute', top: 72, left: 0, right: 0, margin: 'auto' }}
        // footer={modalFooter}
      >
        {node}
        <GoodsFilterForm form={form} onFinish={(values) => {
            if (values.createTime) {
                values.startTime = values.createTime[0].set({ hour: 0, minute: 0, second: 0 }).format('YYYY-MM-DD HH:mm:ss');
                values.endTime = values.createTime[1].set({ hour: 23, minute: 59, second: 59 }).format('YYYY-MM-DD HH:mm:ss');
            }
            delete values.createTime;

            setFilterParams({ priceType: 4, ...values});
        }} collectSelectedRows={() => {
            form.resetFields();
            form.setFieldValue('skuCode', curRows.current.map((item) => item.skuCode).join(','));
            form.submit();
        }} cleanFormValues={() => {
            form.resetFields();
        }}></GoodsFilterForm>
        <GoodsShowTable filterParams={filterParams} setSelectedRows={setSelectedRows} getTableRows={getTableRows} onInputNumberChange={(vals) => {
            curInputNumberValues.current = vals;
        }} type={type} isSingle={isSingle} commonChange={commonChange}></GoodsShowTable>
      </CommonModal>
    </>);
};
export default GoodsSelectModal;
